package models

type Station struct {
	Model
	Name string `json:"name"`
	Lng float64 `json:"lng"`
	Lat float64 `json:"lat"`
	OwnerId int `json:"ownerId" gorm:"owner_id"`
	Status int `json:"status"`
}

func GetStationsForUser(userId int) (stations []Station) {
	db.Table("bms_station").Where("owner_id = ?", userId).Scan(&stations)
	var employments []Employment
	db.Table("bms_employment").Where("employer_id = ? or employee_id =?", userId, userId).Scan(&employments)
	for _, e := range employments {
		var tmp []Station
		db.Where("id = ?", e.StationId).Find(&tmp)
		for _, t := range tmp {
			stations = append(stations, t)
		}
	}
	return
}

func ExistStationByID(id int) bool {
	var station Station
	db.Select("id").Where("id = ?", id).First(&station)
	return station.ID > 0
}

func GetStationSlave(id int) (interface{}, string) {
	var bsus []BSU
	db.Table("bms_bsu").Where("station_id = ?", id).Find(&bsus)
	if len(bsus) > 0 && bsus[0].ID > 0{
		return bsus, "bsu"
	}

	var bcus []BCU
	db.Select("bms_bcu").Where("station_id = ?", id).First(&bcus)
	if len(bcus) > 0 && bcus[0].ID > 0{
		return  bcus, "bcu"
	}

	var bmus []BMU
	db.Select("bms_bmu").Where("station_id = ?", id).First(&bmus)
	if len(bmus) > 0 && bmus[0].ID > 0{
		return bmus, "bmu"
	}
	return nil, "null"
}

func AddStation(name string, lng, lat float64, ownerId, status int) bool {
	db.Create(&Station{
		Name: name,
		Lng: lng,
		Lat: lat,
		OwnerId: ownerId,
		Status: status,
	})
	return true
}

func DeleteStation(id int) bool {
	db.Where("id = ?", id).Delete(&Station{})
	return true
}

func CheckDeleteStation(id int) bool {
	var bmu BMU
	db.Select("id").Where("station_id = ?", id).First(&bmu)
	if bmu.ID > 0{
		return false
	}
	var bcu BCU
	db.Select("id").Where("station_id = ?", id).First(&bcu)
	if bcu.ID > 0{
		return false
	}
	var bsu BSU
	db.Select("id").Where("station_id = ?", id).First(&bsu)
	if bsu.ID > 0{
		return false
	}
	return true
}

func UpdateStation(id int, data interface{}) bool {
	db.Model(&Station{}).Where("id = ?", id).Updates(data)
	return true
}
